package com.fingard.dsp.bank.directbank.gdb01;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.gdb01.util.ReceiptProp;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;

public class GDB01SyncTask extends GDB01Base {

    private String actNum = "";
    private String dateFrom = "";
    private String dateTo = "";
    private String actCur = "";


    public GDB01SyncTask(String p_actNum, String p_actCur, String p_dateFrom, String p_dateTo) {
        actNum = p_actNum;
        actCur = p_actCur;
        dateFrom = p_dateFrom;
        dateTo = p_dateTo;
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void downloadReceipt() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                String uploadType = SmbFileUtil.getUploadType();
                StringBuilder logSb = new StringBuilder();
                try {
                    setSbLog(logSb);

                    ReceiptProp receiptProp = new ReceiptProp(getBankConfig());
                    FtpSet ftpSet = bankFront.getFtpSet("receipt");
                    FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                    try {
                        ftpPtClient.connect();

                        StringBuilder json = new StringBuilder();
                        if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                            json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
                        }else{
                            json.append("transType=downloadreceipt&data={\"rows\":[");
                        }
                        StringBuilder sendToAtsData = new StringBuilder();
                        int totalCount = 0;
                        int downloadSucc = 0;
                        int uploadSucc = 0;

                        Calendar tmpCalendarFrom = Calendar.getInstance();
                        tmpCalendarFrom.setTime(Format.Date8Format.parse(dateFrom));

                        Calendar tmpCalendarTo = Calendar.getInstance();
                        tmpCalendarTo.setTime(Format.Date8Format.parse(dateTo));

                        int tmpIntDateFrom = 0;
                        int tmpIntDateTo = 0;
                        //按自然日循环查询
                        while (tmpIntDateFrom <= tmpIntDateTo) {
                            String qryDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
                            String filePath = receiptProp.getFilePath(ftpSet.downDir, actNum, qryDate);
                            String sumFilePath = receiptProp.getSumFileFullPath(ftpSet.downDir, actNum, qryDate);
                            //if (ftpPtClient.existFile(sumFilePath)) {
                            String localSumFilePath = getTempFileDirectory(tmpCalendarFrom.getTime()) + File.separator + "NewSumFile" + File.separator + receiptProp.getSumFileName(actNum, qryDate);
                            File tmpFile = new File(localSumFilePath);
                            boolean fileExist = false;
                            if (tmpFile.exists()) {
                                WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]汇总文件已存在无需再次下载", actNum, qryDate));
                                fileExist = true;
                            } else {
                                FtpReceiver tmpReceiver = ftpPtClient.downloadFile(sumFilePath, localSumFilePath);
                                if (tmpReceiver.isCompleted) {
                                    fileExist = true;
                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]下载汇总文件成功", actNum, qryDate));
                                } else {
                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]下载汇总文件失败，失败原因：[%s]", actNum, qryDate, tmpReceiver.connMsg));
                                }
                            }

                            if (fileExist) {
                                String sumFileContent = FileHelper.readFileText(localSumFilePath, getCharset());
                                //WriteBankLogLn(sumFileContent);
                                if (StringHelper.hasAnyChar(sumFileContent)) {
                                    String[] eachReceiptInfo = sumFileContent.split("\r\n");
                                    if (eachReceiptInfo != null && eachReceiptInfo.length > 1) {
                                        int receiptCount = eachReceiptInfo.length;
                                        for (int i = 1; i < receiptCount; i++) {
                                            //WriteBankLogLn(eachReceiptInfo[i]);
                                            String[] receiptInfos = (eachReceiptInfo[i] + " ").split("\\|");
                                            //WriteBankLogLn(receiptInfos.length + "");
                                            int actNumIndex = receiptProp.getQryAcctIndex();
                                            String receiptActNum = receiptInfos[actNumIndex].trim();
                                            if (receiptActNum.equals(actNum)) {
                                                totalCount++;
                                                int receiptCodeIndex = receiptProp.getBankNoIndex();
                                                String receiptCode = receiptInfos[receiptCodeIndex];
                                                String receiptName = receiptCode + ".pdf";
                                                String tmpByDate = Format.Date8Format.format(new Date());
                                                tmpByDate = tmpByDate.substring(0, 6) + File.separator + tmpByDate.substring(6, 8) + File.separator + reqHeader.bankCode + File.separator + actNum + File.separator;
                                                String localReceiptPath = StringHelper.trimEnd(FGBiz.dspCenter.dspSet.receiptMainDir, File.separator) + File.separator + tmpByDate + receiptName;
                                                boolean isReceiptExist = false;
                                                File tmpReceiptFile = new File(localReceiptPath);
                                                if (tmpReceiptFile.exists()) {
                                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]，回单编号：[%s]回单文件已存在无需再次下载", actNum, qryDate, receiptCode));
                                                    isReceiptExist = true;
                                                } else {
                                                    String remoteReceiptPath = filePath + receiptName;
                                                    FtpReceiver tmpReceiptReceiver = ftpPtClient.downloadFile(remoteReceiptPath, localReceiptPath);
                                                    if (tmpReceiptReceiver.isCompleted) {
                                                        isReceiptExist = true;
                                                        WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]，回单编号：[%s]回单文件已成功下载", actNum, qryDate, receiptCode));
                                                    } else {
                                                        WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]，回单编号：[%s]回单文件下载失败，失败原因：[%s]", actNum, qryDate, receiptCode, tmpReceiptReceiver.connMsg));
                                                    }
                                                }

                                                if (isReceiptExist) {
                                                    downloadSucc++;
                                                    int result;
                                                    String ftpFilePath = "";
                                                    String AtsFilePath = "";
                                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                        if ("smb".equals(uploadType)) {
                                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            result = SmbFileUtil.smbUploading(localReceiptPath, tmpByDate.replace(File.separator, "/"), FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            AtsFilePath = tmpByDate.replace(File.separator, "/") + receiptName;
                                                        } else {
                                                            tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                                            WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            Map<String, String> map = FormSubmit.fileUpload
                                                                    (FGBiz.dspCenter.dspSet.receiptShareDir, actNum, localReceiptPath, tmpByDate, receiptName, getCharset());
                                                            WriteBankLogStep3(JSON.toJSONString(map));
                                                            if (map.keySet().size() != 0) {
                                                                result = Integer.valueOf(map.get("respCode"));
                                                                tmpByDate = map.get("remotePath");
                                                                AtsFilePath = tmpByDate;
                                                            } else {
                                                                result = -1;
                                                            }
                                                        }
                                                    } else {
                                                        //ftp服务器
                                                        FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                                        AtsFilePath = tmpByDate.replace(File.separator, "/") + receiptName;//回单文件仓库存储路径
                                                        //上传ftp服务器的地址
                                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                                        WriteBankLogLn("开始将回单" + localReceiptPath + "上传至" + ftpFilePath);
                                                        //上传至ftp
                                                        result = FtpUtil.ftpUploading(ftpSet3, localReceiptPath, ftpFilePath);
                                                    }
                                                    if (result == 0 || result == 1) {
                                                        uploadSucc++;
                                                        if (result == 0) {
                                                            WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]，回单编号：[%s]回单文件已上传成功", actNum, qryDate, receiptCode));
                                                        } else {
                                                            WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]，回单编号：[%s]回单文件已存在，无需重复上传", actNum, qryDate, receiptCode));
                                                        }

                                                        int oppActNumIndex = receiptProp.getOppAcctIndex();
                                                        String oppActNum = receiptInfos[oppActNumIndex].trim();
                                                        int moneywayIndex = receiptProp.getCDFlagIndex();
                                                        String moneyway = receiptInfos[moneywayIndex].trim();
                                                        int tranSeqNoIndex = receiptProp.getCorpNoIndex();
                                                        String tranSeqNo = receiptInfos[tranSeqNoIndex].trim();
                                                        String transDate = Format.Date10Format.format(tmpCalendarFrom.getTime());

                                                        //推送数据给ATS处理
                                                        sendToAtsData.append("{");
                                                        sendToAtsData.append("\"actNum\":\"" + actNum + "\",");
                                                        sendToAtsData.append("\"actCur\":\"" + actCur + "\",");
                                                        sendToAtsData.append("\"receiptCode\":\"" + receiptCode + "\",");//回单编号
                                                        sendToAtsData.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                                        sendToAtsData.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                                        sendToAtsData.append("\"oppActName\":\"" + "" + "\",");
                                                        sendToAtsData.append("\"oppActNum\":\"" + oppActNum + "\",");
                                                        sendToAtsData.append("\"amount\":\"" + "" + "\",");
                                                        sendToAtsData.append("\"moneyway\":\"" + ("D-借".equals(moneyway) ? "1" : "2") + "\",");
                                                        sendToAtsData.append("\"tranSeqNo\":\"" + receiptCode + "\",");
                                                        sendToAtsData.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                                        sendToAtsData.append("\"tranDate\":\"" + transDate + "\",");
                                                        sendToAtsData.append("\"filePath\":\"" + AtsFilePath + "\",");//文件路径
                                                        sendToAtsData.append("\"fileType\":\"1\"");
                                                        sendToAtsData.append("},");
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]对应的汇总文件经检测无回单信息", actNum, qryDate));
                                    }
                                } else {
                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]对应的汇总文件经检测为空", actNum, qryDate));
                                }
                            }
                            /*} else {
                                WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]未检测到回单文件", actNum, qryDate));
                            }*/
                            tmpCalendarFrom.add(Calendar.DATE, 1);
                            tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                            tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                        }

                        if (sendToAtsData.toString().length() > 0) {
                            sendToAtsData.deleteCharAt(sendToAtsData.length() - 1);
                            sendToAtsData.append("]}");
                            String sendToAtsStr = json.toString() + sendToAtsData.toString();
                            String[] data;
                            String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                            if ("nbGateway".equals(receiptPushType)) {
                                WriteBankLogLn("3.推送给网关的数据" + receiptPushType.toString());
                                DirectBase tmplogMsg = new DirectBase();
                                data = FormSubmit.receiptInfoSend(receiptPushType.toString(), new DirectBase(), false);
                                WriteBankLogLn(tmplogMsg.getSbLog());
                                if (data[0].length() == 0 && data[1].equals("ok")) {
                                    WriteBankLogLn("推送数据到网关成功,请查看数据");
                                } else {
                                    WriteBankLogLn("推送数据到网关失败");
                                }
                            } else {
                                WriteBankLogLn("3.推送给ATS的数据" + receiptPushType.toString());
                                data = sendToATS(json.toString());
                                if (data[0].length() == 0 && data[1].equals("ok")) {
                                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                                } else {
                                    WriteBankLogLn("推送数据到ATS失败");
                                }
                            }
                        } else {
                            WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
                        }

                        WriteBankLogLn(String.format("总计：[%s笔]回单，下载成功：[%s笔]，上传成功:[%s笔]", totalCount, downloadSucc, uploadSucc));
                        WriteBankLogLn(String.format("针对账号：[%s]，起始日期：[%s]，结束日期:[%s]的回单下载任务已完成执行", actNum, dateFrom, dateTo));
                    } catch (Exception ex) {
                        WriteBankLogLn(ex);
                        ftpPtClient.disconnect();
                    }
                } catch (Exception ex) {
                    WriteBankLogLn(ex);
                    ex.printStackTrace();
                } finally {
                    String tmpDateDir = Format.DateForLogFormat.format(new Date()).replace("-", File.separator);
                    String tmpSubFileName = FGBiz.dspCenter.bankLogsFirstDir + File.separator + tmpDateDir + File.separator + "GDB01" + File.separator + "SyncTask-downloadReceipt" + "_" + actNum + "_" + Format.DateTime14Format.format(new Date()) + "_" + UUID.randomUUID() + ".txt";
                    String tmpLogFile = FGBiz.dspCenter.bankLogsDirPath + File.separator + tmpSubFileName;
                    try {
                        FileHelper.writeFile(tmpLogFile, logSb);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
}
